package yweb

import (
	"log"
	"net/http"
	"time"
	"yweb/context"
)

var (
	YWebApp *App
)

func init() {
	YWebApp = NewApp()
}

type App struct {
	Handles *ControllerRegister
	Server  http.Server
}

func NewApp() *App {
	//创建APP
	app := &App{Handles: NewControllerRegister()}
	//路由
	app.Handles = NewControllerRegister()

	return app
}

func (app *App) Run() {

	server := http.Server{
		Addr:        ":8081",
		Handler:     &myHandle{},
		ReadTimeout: 5 * time.Second,
	}
	YWebApp.Server = server

	log.Println("已为您启动了服务，您可以打开浏览器访问 127.0.0.1:8081 ，我会输入访问日志。")

	err := server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}

}

type myHandle struct{}

func (*myHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	log.Println("请求url:", r.URL.String())
	log.Println("请求方法:", r.Method)

	//解析，默认不解析的，否者r.Form将拿不到数据
	r.ParseForm()

	log.Println("请求报文:", r)
	log.Println("请求的参数:", r.Form)

	//生成这次的请求体等
	ctx := context.NewContext()
	ctx.Reset(w, r)

	//url
	url := r.URL.String()

	//获取对应的控制器
	ctr := YWebApp.Handles.routers[url]

	//判断路由是否存在
	if ctr == nil {
		log.Println("没找到路由")
		StaticServerBegin(ctx)
		return
	}

	//初始化控制
	ctr.Init(ctx)

	//方法
	method := r.Method

	switch method {
	case "GET":
		ctr.Get()
	case "POST":
		ctr.Post()
	default:
		ctr.Get()
	}

	ctr.Show()

}

func Router(path string, c ControllerInterface) {
	log.Println(path)
	log.Println(c)

	YWebApp.Handles.Add(path, c)
}
